﻿using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.Law.Dto;
using Com.JunCaiSoft.Law.Entity;
using Com.JunCaiSoft.Law.IDao;
using Com.JunCaiSoft.Law.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.Law.Controllers
{
    /// <summary>
    /// 解冻申请
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UnFreezingApplicationController : BaseController<UnFreezingApplicationView, UnFreezingApplicationItem, UnFreezingApplication, Guid>
    {
        public UnFreezingApplicationController(IUnFreezingApplicationDao UnFreezingApplicationDao) : base(UnFreezingApplicationDao)
        {

        }
        /// <summary>
        /// 按保全ID单个删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public override async Task<ActionResult> DeleteSingleAsync(Guid Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();
                int result = await DaoAsync.DeleteListAsync<UnFreezingApplication>(x => x.Id == Id);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 按保全ID批量删除
        /// </summary>
        /// <param name="DeleteList"></param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> DeleteList)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = await DaoAsync.DeleteListAsync<UnFreezingApplication>(x => DeleteList.Contains(x.Id));

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize"></param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize, String keyword)
        {
            try
            {
                var columns = @" f.Id,
	                             f.Num,
	                             f.NumCode,
	                             b.Name BankName,
	                             b.Account Account,
	                             p.Name Project,
	                             f.FreezeConfirm,
	                             f.UnFreezingApplicationCode,
	                             f.AccpectCourt,
	                             j.Name JudgeResult,
	                             f.ProjectManager,
	                             f.Plaintiff,
	                             f.JudgmentTime,
	                             f.DeadLine,
	                             c.Name UnFreezingApplicationStatus,
	                             f.CourtFreeze,
	                             f.FactFreeze,
	                             f.JudgmentMoney,
	                             f.Amount,
	                             f.FreezeTime,
	                             f.UnFreezeTime,
	                             f.FreezeRateType,
	                             f.FreezeRate,
	                             f.FreezeLoanConfirm,
	                             f.Remark,
	                             f.Accountant,
	                             u.RealName FreezeOperator,
	                             f.CreateTime  ";

                var tables = @" UnFreezingApplication f
	                            LEFT JOIN Bank b ON f.FreezeBank = b.Id
	                            LEFT JOIN Project p ON f.FreezeProject = p.Id
                                LEFT JOIN UnFreezingApplicationType c on f.UnFreezingApplicationStatus = c.Code
                                LEFT JOIN JudgeResults j on f.JudgeResult = j.Code
	                            LEFT JOIN [User] u on f.FreezeOperatorId = u.Id ";

                var where = @" 1 = 1 ";

                List<SqlParameter> bankParams = new List<SqlParameter>() { };

                if (keyword != "" && keyword != null)
                {

                    Regex rex = new Regex(@"^\d{4}$");

                    if (keyword.Length == 4 && rex.IsMatch(keyword))
                    {
                        where += " AND f.Account like @BankNameOrBankTail ";

                        SqlParameter QueryBankName = new SqlParameter("@BankNameOrBankTail", "%" + keyword);

                        bankParams.Add(QueryBankName);
                    }
                    else
                    {
                        where += " AND b.Name like @BankNameOrBankTail OR p.Name like @BankNameOrBankTail ";

                        SqlParameter QueryBankName = new SqlParameter("@BankNameOrBankTail", "%" + keyword + "%");

                        bankParams.Add(QueryBankName);
                    }

                }

                var tmpResultList = await DaoAsync.QuerySQLByPageQuickAsync<UnFreezingApplicationItemDto>(pageIndex, pageSize, " f.CreateTime desc ", columns, tables, where, bankParams.Select(x => ((ICloneable)x).Clone()).ToArray());

                var resultList = new QueryData<UnFreezingApplicationItem>();

                var itemList = new List<UnFreezingApplicationItem>();

                resultList.totalCount = tmpResultList.totalCount;

                tmpResultList.items.ToList().ForEach(item => itemList.Add(item.MapTo<UnFreezingApplicationItem>()));

                resultList.items = itemList;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(resultList)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 创建保全信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<ActionResult> CreateAsync(UnFreezingApplicationView entity)
        {
            try
            {
                DaoAsync.dbContext.Database.BeginTransaction();

                var saveone = entity.MapTo<UnFreezingApplication>();
                var result = await DaoAsync.InsertAsync(saveone);

                DaoAsync.dbContext.Database.CommitTransaction();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        /// <summary>
        /// 更新保全信息
        /// </summary>
        /// <param name="entityModel"></param>
        /// <returns></returns>
        [HttpPut]
        public override async Task<ActionResult> UpdateAsync(UpdateEntity<UnFreezingApplicationView> entityModel)
        {
            DaoAsync.dbContext.Database.BeginTransaction();

            var saveone = entityModel.entity.MapTo<UnFreezingApplication>();
            var result = await DaoAsync.UpdateAsync(saveone, entityModel.Id);

            DaoAsync.dbContext.Database.CommitTransaction();
            return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
        }
    }
}
